<?php

namespace app\service;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use think\Response;

class ExcelExport
{
    protected $spreadsheet;

    public function __construct()
    {
        $this->spreadsheet = new Spreadsheet();
    }

    public function setCellValue($cellId, $value)
    {
        $this->spreadsheet->getActiveSheet()->setCellValue($cellId, $value);
    }

    public function export($fileName = 'export.xlsx')
    {
        $writer = new Xlsx($this->spreadsheet);

        // 清除缓冲区并关闭输出缓冲
        ob_end_clean();
        // 设置HTTP头信息
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');

        // 将文件写入到输出流中
        $writer->save('php://output');
        exit;
    }
}
